<template>
    <div class="kt-form-table">
        <el-table :key="toggleIndex" ref="tableRef" :data="data" border stripe>
            <el-table-column fixed="left" type="index" align="center" width="60">
                <template #header>
                    <slot name="create" :template="addTemplate"/>
                </template>
                <template #default="scope">
                    <div class="kt-form-table-remove">
                        <span>{{ scope.$index + 1 }}</span>
                        <slot name="remove" :row="scope.row" :$index="scope.$index" :column="scope.column" />
                    </div>
                </template>
            </el-table-column>
            <el-table-column v-if="dragSort" label="" width="58">
                <template #default>
                    <el-tag class="move" style="cursor: move;">
                        <el-icon-d-caret style="width: 1em; height: 1em;"/>
                    </el-tag>
                </template>
            </el-table-column>
            <slot></slot>
            <template #empty>
                {{ placeholder }}
            </template>
        </el-table>
    </div>
</template>

<script lang="ts" setup>
import Sortable from 'sortablejs'
import {nextTick, onMounted, ref, useSlots} from "vue";
const props = defineProps({
    addTemplate: {
        type: Object,
        default: () => {}
    },
    placeholder: {type: String, default: "暂无数据"},
    dragSort: {type: Boolean, default: false}
});

const data = defineModel<Array<any>>({default: []});

const tableRef = ref();
const toggleIndex = ref(0);

onMounted(() => {
    if (props.dragSort) {
        onRowDrop()
    }
})

const onRowDrop = () => {
    const tbody = tableRef.value.$el.querySelector('.el-table__body-wrapper tbody')
    Sortable.create(tbody, {
        handle: ".move",
        animation: 300,
        ghostClass: "ghost",
        onEnd({newIndex, oldIndex}: any) {
            const tableData = data.value
            const currRow = tableData.splice(oldIndex, 1)[0]
            tableData.splice(newIndex, 0, currRow)
            toggleIndex.value += 1
            nextTick(() => {
                onRowDrop()
            })
        }
    })
}

const onRowAdd = () => {
    data.value.push(props.addTemplate)
}

const onRowDel = (row: any, index: number) => {
    data.value.splice(index, 1)
}
</script>

<style >
.kt-form-table {
    width: 100%;
}

.kt-form-table .kt-form-table-remove {
    text-align: center;
}

.kt-form-table .kt-form-table-remove span {
    display: inline-block;
}

.kt-form-table .kt-form-table-remove button {
    display: none;
}

.kt-form-table .hover-row .kt-form-table-remove span {
    display: none;
}

.kt-form-table .hover-row .kt-form-table-remove button {
    display: inline-block;
}
</style>
